package per.sunmes.lesrb.listener;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;

import per.sunmes.lesrb.apis.CallBackObj;
import per.sunmes.lesrb.manager.SM;

public class ColorChangeBtnListener extends InputListener {

	private String btnSoundPath;
	public static String defaultBtnSoundPath;

	private CallBackObj<Actor> callback;
	float touchX;
	boolean isTouched = false;
	int touchPointer, touchButton;

	public ColorChangeBtnListener(CallBackObj<Actor> action) {
		callback = action;
		if (defaultBtnSoundPath != null) {
			btnSoundPath = defaultBtnSoundPath;
		}
	}

	public ColorChangeBtnListener(CallBackObj<Actor> action, String sound) {
		callback = action;
		btnSoundPath = sound;
	}

	@Override
	public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
		if (isTouched) {
			return false;
		}
		isTouched = true;
		touchPointer = pointer;
		touchButton = button;

		touchX = event.getStageX();
		setActorColor(event.getListenerActor(), Color.GRAY);

		if (btnSoundPath != null && !btnSoundPath.isEmpty()) {
			SM.playAssetSound(btnSoundPath);
		}

		return true;
	}

	public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
		if (!isTouched) {
			return;
		}
		if (pointer == touchPointer || button == touchButton) {
			isTouched = false;
		} else {
			return;
		}

		if (Math.abs(event.getStageX() - touchX) > 20) {
			setActorColor(event.getListenerActor(), Color.WHITE);
			return;
		}
		if (event.getListenerActor().hit(x, y, true) != null) {
			setActorColor(event.getListenerActor(), Color.WHITE);
			callback.call(event.getListenerActor());
		} else {
			setActorColor(event.getListenerActor(), Color.WHITE);
		}
	};

	public static void setActorColor(Actor actor, Color color) {
		if (actor instanceof Group) {
			for (Actor ca : ((Group) actor).getChildren()) {
				setActorColor(ca, color);
			}
		} else {
			actor.setColor(color);
		}

	}

	public static void setActorColor(Actor actor, float r, float g, float b, float a) {
		setActorColor(actor, new Color(r, g, b, a));
	}

}
